package com.jeecms.wicool.dao.shops.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.common.hibernate3.Finder;
import com.jeecms.common.hibernate3.HibernateBaseDao;
import com.jeecms.common.page.Pagination;
import com.jeecms.wicool.dao.shops.CouponDao;
import com.jeecms.wicool.entity.shops.Coupon;
import com.jeecms.wicool.entity.user.UserCoupon;

@Repository
public class CouponDaoImpl extends HibernateBaseDao<Coupon, Integer> implements
		CouponDao {

	@Override
	protected Class<Coupon> getEntityClass() {
		// TODO Auto-generated method stub
		return Coupon.class;
	}

	@Override
	public Pagination getPage(Integer couponType, String couponName,
			Short status, int pageNo, int pageSize, CmsUser user) {
		Finder f = Finder.create("select bean from Coupon bean where 1=1 ");
		if (couponType != null) {
			f.append(" and bean.couponType = :couponType");
			f.setParam("couponType", couponType);
		}
		if (!StringUtils.isBlank(couponName)) {
			f.append(" and bean.couponName = :couponName");
			f.setParam("couponName", couponName);
		}if (status != null) {
			f.append(" and bean.status = :status");
			f.setParam("status", status);
		}if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		f.append(" order by bean.createTime desc");
		return find(f, pageNo, pageSize);
	}

	@Override
	public Coupon findById(Integer id) {
		Coupon entity = get(id);
		return entity;
	}

	@Override
	public Coupon save(Coupon bean) {
		getSession().save(bean);
		return bean;
	}

	@Override
	public Coupon deleteById(Integer id) {
		Coupon entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	@Override
	public List<Coupon> getAll(CmsUser user) {
		Finder f = Finder
				.create("select bean from Coupon bean where 1 = 1 ");
		if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		f.append(" order by bean.id desc");
		return find(f);
	}

	public List<UserCoupon> findByCouponId(Integer couponId){
		Finder f = Finder.create("select bean from UserCoupon bean where bean.coupon.id="+couponId);
		return find(f);
	}
	
}